package com.ruoyi.common.utils.digest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.io.Serializable;

/**
 * ByteSource对象
 *
 * @author 李志慧
 * @date 2017年6月20日.
 */
public class ByteSource implements Serializable {

    /**
     * 原始字节数组
     */
    private byte[] bytes;

    /**
     * 默认构造对象
     */
    public ByteSource() {
    }

    /**
     * 根据bytes构造ByteSource对象
     *
     * @param bytes 字节数组
     */
    public ByteSource(byte[] bytes) {
        this.bytes = bytes;
    }

    /**
     * 获取字节数组
     *
     * @return 字节数组
     */
    public byte[] getBytes() {
        return bytes;
    }

    /**
     * 将数组对象转化为base64字符串
     *
     * @return base64字符串
     */
    public String toBase64() {
        return Base64.encodeBase64String(this.bytes);
    }

    /**
     * 将数组转化为Hex数组
     *
     * @return Hex数组
     */
    public String toHex() {
        if (this.bytes == null) {
            return null;
        }
        if (this.bytes.length == 0) {
            return "";
        }
        return Hex.encodeHexString(this.bytes);
    }

    @Override
    public String toString() {
        if (this.bytes == null) {
            return null;
        }
        if (this.bytes.length == 0) {
            return "";
        }

        StringBuffer sb = new StringBuffer("ByteSource[" + bytes.length + "]{");
        int size = sb.length();
        for (byte b : bytes) {
            if (sb.length() > size) {
                sb.append(", ");
            }
            sb.append(b);
        }
        sb.append("}");
        return sb.toString();
    }

    /**
     * 判断对象内容是否为空
     *
     * @return 对象内容是否为空
     */
    public boolean isEmpety() {
        return bytes == null || bytes.length == 0;
    }

    public ByteSource fromHex(String hexString) {
        try {
            this.bytes = Hex.decodeHex(hexString.toCharArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return this;
    }

    public ByteSource fromBase64(String base64String) {
        try {
            this.bytes = Base64.decodeBase64(base64String);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return this;
    }
}
